package sword;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 题目：输入一个链表，按链表值从尾到头的顺序返回一个ArrayList。用栈存放列表值
 * @author longzj
 */
public class ReadListNodes {

    public static void main(String[] args) {
        ListNode firstNode = new ListNode(67);
        ListNode node1 = new ListNode(0);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(2);
        firstNode.next = node1;
        node1.next = node2;
        node2.next = node3;

        ReadListNodes nodes = new ReadListNodes();
        ArrayList<Integer> list = nodes.printListFromTailToHead(firstNode);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }

    private ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        if (!stack.isEmpty()) {
            while (stack.peek() != null) {
                list.add(stack.pop());
                if (stack.isEmpty()) {
                    break;
                }
            }
        }
        return list;
    }


    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

}
